import { Injectable, HttpService, HttpException, HttpStatus } from '@nestjs/common';
import { CodeSendDTO } from './third.dto'
import * as dateFns from 'date-fns'
import { Between } from 'typeorm';
import * as crypto from "crypto";
import * as xml2js from 'xml2js'
import * as db from '../../entity'

@Injectable()
export class ThirdService {
    constructor(private readonly httpService: HttpService) { }

    async sendCode(mobileInfo: CodeSendDTO, type: db.SmsCodeTypeEnum) {
        const findMobileCount = await db.MobileSms.count({
            where: {
                mobile: mobileInfo.data.phone,
                create_time: Between(dateFns.startOfDay(new Date()), dateFns.endOfDay(new Date())),
            }
        })
        if (findMobileCount > 10) {
            throw new HttpException('同一个手机号一天只能发送10条短信', HttpStatus.EXPECTATION_FAILED);
        }
        const code = String(Math.floor(Math.random() * 1000000)).substr(-4);
        const enPassword = function () {
            const hash = crypto.createHash('md5');
            hash.update('yzwl@hy');
            return hash.digest('hex').toLocaleLowerCase();
        }();
        const message = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><MtMessage><content>【羿正科技】您的短信验证码是${code}，10分钟有效！</content><phoneNumber>${mobileInfo.data.phone}</phoneNumber></MtMessage>`;
        const param = {
            account: 'xindaibs',
            password: enPassword,
            smsType: "yizheng",
            message: message
        }
        const url = 'http://sms.easyct.net:8001/http/submitSms';
        try {
            await this.httpService.get(url, {
                params: param,
                headers: {
                    "Content-Type": 'text/html;charset=utf-8'
                }
            }).subscribe((rsp) => {
                xml2js.parseString(rsp.data, { explicitArray: false }, async function (err, body) {
                    if (err) {
                        throw new HttpException('服务器出错', HttpStatus.EXPECTATION_FAILED);
                    } else {
                        if (body.MtMessageRes.resDetail.stat == 'r:000') {
                            const sms = db.MobileSms.create({
                                mobile: mobileInfo.data.phone,
                                code: String(code),
                                expire_time: dateFns.addMinutes(new Date(), 10),
                                type: type
                            })
                            await sms.save();
                            return;
                        } else {
                            throw new HttpException(body.MtMessageRes.resDetail.statDes, HttpStatus.EXPECTATION_FAILED);
                        }
                    }
                });
            });
        } catch{
            throw new HttpException('调用网络接口出错', HttpStatus.EXPECTATION_FAILED);
        }
    }
}